// ==UserScript==
// @name            The West - Common tools [SOM]
// @description     The West - Common tools for SOM scripts [SOM - Scripts-O-Maniacs]
// @namespace       http://scripts-o-maniacs.leforum.eu/
// @author          Danosaure
// @release         Danosaure
// @include         http://*.the-west.*/game.php*
// @include         http://userscripts.org/scripts/review/120825*
// @include         http://userscripts.org/scripts/source/120825.meta.js*
// @version         1.0.5
// @copyright       2011, Danosaure (http://scripts-o-maniacs.leforum.eu/)
// @website         http://scripts-o-maniacs.leforum.eu
//
// @history         1.0.5|2011.12.23    Fix pour l'iframe.
// @history         1.0.4|2011.12.20    Modifications for include testing to avoid error.
// @history         1.0.3|2011.12.19    Modified to look like the one in TWPro+.
// @history         1.0.2|2011.12.19    Cleaning up iframe.
// @history         1.0.1|2011.12.19    First functional version.
// @history         1.0.0|2011.12.18    Created
// ==/UserScript==

// Numéros du script: prod:120825 beta:YYYYYY
// $Revision: 112 $
// $Date:: 2011-12-24 05:37:35 #$

if (
        (window.location.href.indexOf('.the-west.') != -1)
        && (window.location.href.indexOf('game.php') != -1)
        ){
    // Script running in-game.
    (
        function(f) {
            var s = document.createElement('script');
            s.type = 'application/javascript';
            s.textContent = '(' + f.toString() + ')()';
            (document.body || document.head || document.documentElement).appendChild(s);
            s.parentNode.removeChild(s);
        }
    )(
        function() {
            if (typeof(SOM) == 'undefined') {
                // No other SOM scripts have been loaded yet.
                SOM = new Object();
            }

            SOM.NB_HISTORY = 5;
            SOM.DELTA_MAJ = 24 * 60 * 60; // 24h
            SOM.USO_URL = 'http://userscripts.org';

            /**
             * Gets an object from the localStorage. Objects are saved with
             * SOM.setObject(key, value) method.
             */
            SOM.getObject = function(key) {
                var value = localStorage.getItem(key);
                if (value == null) {
                    // Was not defined.
                    return null;
                }

                if ((value[0] == '{') && (value[value.length-1] == '}')) {
                    // Potentially previously JSON.stringify() value.
                    try {
                        return JSON.parse(value);
                    } catch (e) {
                        // Badly JSON.stringify()
                        return value;
                    }
                }
                return value;
            };

            /**
             * Sets an object into the localStorage. Objects are retreived with
             * SOM.getObject(key) method.
             */
            SOM.setObject = function(key, value) {
                if (typeof(value) == 'object') {
                    value = JSON.stringify(value);
                }
                localStorage.setItem(key, value);
            };

            /**
             * Deletes an object from the localStorage and returns its current
             * value.
             */
            SOM.delObject = function(key) {
                return localStorage.removeItem(key);
            };

            /**
             * Creates a DOM element and append it to the parent.
             */
            SOM.createElement = function(p, tag) {
                var el = document.createElement(tag);
                p.appendChild(el);
                return el;
            };

            /**
             * Creates a DOM text node and append it to the parent.
             */
            SOM.createTextNode = function(p, text) {
                var el = document.createTextNode(text);
                p.appendChild(el);
                return el;
            };

            /**
             * Adds a mouseover popup with the message in bold.
             */
            SOM.popup = function(element, message) {
                element.addMousePopup(new MousePopup('<b>' + message + '</b>'));
            };

            if (typeof(SOM.Tools) != 'undefined') {
                // There may be a conflict with the script.
                new HumanMessage("Conflict loading. Disable other versions of this script.");
                return;
            }
            // This script has not been loaded yet.
            SOM.Tools = new Object();

            SOM.Tools.VERSION = '1.0.5';
            SOM.Tools.NUMERO_SCRIPT = '120825';

            /**
             * Determines if in Safari browser.
             */
            SOM.Tools.is_safari = function() {
                var navigateur = navigator.userAgent.toLowerCase();
                return ((navigateur.indexOf('chrome') == -1)
                        && (navigateur.indexOf('safari') != -1));
            };

            /**
             * Fenêtre pour la mise à jour si nécessaire.
             */
            /**
             * Mettre à jour la version du script si nécessaire.
             */
            SOM.Tools.mettre_a_jour = function(version_courante, numero_script) {
                var cle = 'SOM_' + numero_script + '_MAJ';

                var heure_actuelle = new Date().getTime() / 1000;
                //var prochaine_maj = SOM.getObject(cle) || (heure_actuelle - 1000);
                var prochaine_maj = 0;
                if (prochaine_maj <= heure_actuelle) {
                    var script_url = SOM.USO_URL + '/scripts/source/' + numero_script + '.meta.js';

                    if (SOM.Tools.is_safari()) {
                        script_url = SOM.USO_URL + '/scripts/review/' + numero_script;
                    }

                    // Écriture dans une iframe le contenu de la source de l'en-tête du script.
                    var iframe = SOM.createElement(document.body, 'iframe');
                    iframe.id = 'som_' + numero_script + '_maj';
                    // --- PROD ---
                    iframe.style.display = 'none';
                    // --- /PROD ---

                    // --- DEBUG ---
                    //iframe.style.display = 'inline';
                    //iframe.style.zIndex = 100;
                    //iframe.style.backgroundColor = 'white';
                    //iframe.style.position = 'absolute';
                    //iframe.style.width = '900px';
                    //iframe.style.height = '600px';
                    // --- /DEBUG ---
                    iframe.src = script_url;

                    // Fix for iframe bad content loading.
                    var f = document.getElementsByTagName('iframe');
                    for (var i = 0; i < f.length; i++) {
                        if (f[i].src.substr(0, 31) == 'http://www.jeux-alternatifs.com') {
                            continue;
                        } else if (f[i].src.substr(f[i].src.length - 1) == '#') {
                            f[i].src = f[i].src.substr(0, f[i].src.length - 1);
                        } else {
                            f[i].src = f[i].src + '#';
                        }
                    }

                    var trait_ret_iframe = function(version_actuelle, numero_script) {
                        var ouvrir_lien_script = function() {
                            try {
                                if (SOM.Tools.is_safari()) {
                                    window.open(SOM.USO_URL + '/scripts/show/' + numero_script);
                                } else {
                                    location.href = SOM.USO_URL + '/scripts/source/' + numero_script + '.user.js';
                                }
                            } catch (e) {
                            }
                        };

                        var make_script_history = function(tbody, span_next, tab_history, debut) {
                            var f = arguments.callee;
                            return function(e) {
                                var i;
                                var history_precedent = '';
                                var nb_history = 0;
                                var ligne, ligne_info, info_history;
                                var tr, td, el, ul, li;

                                for (i = debut;
                                        (i < tab_history.length) && (nb_history < SOM.NB_HISTORY);
                                        i++) {
                                    ligne = tab_history[i].match(/\/\/ @history+\s*(.*)/)[1];
                                    ligne_info = ligne.match(/^([a-zA-Z0-9\.\-\|\/]*)\s*(.*)/);
                                    info_history = ligne_info[1].split('|');

                                    if (info_history[0] == history_precedent) {
                                        li = SOM.createElement(ul, 'li');
                                        SOM.createTextNode(li, ligne_info[2]);
                                    } else {
                                        history_precedent = info_history[0];
                                        nb_history++;

                                        tr = SOM.createElement(tbody, 'tr');

                                        td = SOM.createElement(tr, 'td');
                                        td.style.width = '500px';
                                        td.style.border = '1px solid #666666';
                                        td.style.backgroundImage = 'url(../images/profile/settings_profile_input_bg.png)';
                                        td.style.fontSize = '12px';
                                        td.style.verticalAlign = 'top';

                                        el = SOM.createElement(td, 'b');
                                        el.style.marginLeft = '4px';
                                        SOM.createTextNode(el, info_history[0]);

                                        if (2 <= info_history.length) {
                                            el = SOM.createElement(td, 'span');
                                            el.style.cssFloat = 'right';
                                            el.style.fontSize = '10px';
                                            el.style.fontStyle = 'italic';
                                            el.style.marginRight = '4px';
                                            SOM.createTextNode(el, info_history[1]);
                                        }

                                        SOM.createElement(td, 'br');

                                        ul = SOM.createElement(td, 'ul');
                                        ul.style.marginBottom = '4px';

                                        li = SOM.createElement(ul, 'li');
                                        SOM.createTextNode(li, ligne_info[2]);
                                    }
                                } // --- /for

                                if (i < tab_history.length) {
                                    // Il reste encore des trucs dans le history.
                                    span_next.onclick = f(tbody, span_next, tab_history, i);
                                    span_next.innerHTML = '[+' + Math.min(SOM.NB_HISTORY, tab_history.length - i) + ']';
                                } else {
                                    // Il ne reste plus rien.
                                    span_next.style.display = 'none';
                                }
                            };
                        };

                        return function(contenu_iframe) {
                            if (contenu_iframe.origin != SOM.USO_URL) {
                                // Sort si le retour n'est pas le contenu d'un script.
                                return;
                            }

                            var version_recuperee = unescape(contenu_iframe.data);

                            var prochaine_maj = (new Date().getTime() / 1000) + SOM.DELTA_MAJ;
                            try {
                                if (version_recuperee.match(/^\d+/) == numero_script) {
                                    // Le message commence par le bon numéro de script.
                                    var script_version;

                                    // Récupérer le contenu après @version
                                    script_version = version_recuperee.match(/\/\/ @version+\s*(.*)/)[1];

                                    if (script_version != version_actuelle) {
                                        var script_nom, script_auteur, tab_history;
                                        var div, span, table, tbody, tr, td, el, ul, li;
                                        var contenant;

                                        // Récupérer contenu après @name
                                        script_nom = version_recuperee.match(/\/\/ @name+\s*(.*)/)[1];

                                        // Récupérer contenu après @release
                                        script_auteur = version_recuperee.match(/\/\/ @release+\s*(.*)/)[1];

                                        // Récupérer tableau des lignes @history
                                        tab_history = version_recuperee.match(/\/\/ @history+\s*(.*)/g);

                                        // On a fini avec l'history. Faire le ménage dans la page web.
                                        var iframe = $('som_' + numero_script + '_maj');
                                        iframe.parentNode.removeChild(iframe);

                                        contenant = document.createElement('div');

                                        div = SOM.createElement(contenant, 'div');
                                        div.style.textAlign = 'center';
                                        div.style.fontWeight = 'bold';
                                        SOM.createTextNode(div, script_nom);
                                        SOM.createTextNode(div, " ");

                                        span = SOM.createElement(div, 'span');
                                        span.style.fontSize = '9px';
                                        SOM.createTextNode(span, version_actuelle);
                                        SOM.createElement(div, 'br');
                                        span = SOM.createElement(div, 'span');
                                        SOM.createTextNode(span, "The current version is ");
                                        el = SOM.createElement(div, 'strong');
                                        el.style.color = 'rgb(34, 34, 136)';
                                        SOM.createTextNode(el, script_version);

                                        div = SOM.createElement(contenant, 'div');
                                        div.id = 'script_' + numero_script + '_history';
                                        div.style.border = '1px #dabf83 inset';
                                        div.style.overflow = 'auto';
                                        div.style.height = '250px';
                                        div.style.marginTop = '3px';

                                        table = SOM.createElement(div, 'table');

                                        tbody = SOM.createElement(table, 'tbody');

                                        div = SOM.createElement(div, 'div');
                                        div.style.textAlign = 'center';
                                        div.style.fontStyle = '10px';
                                        div.style.marginTop = '-3px';

                                        el = SOM.createElement(div, 'span');
                                        el.style.cursor = 'pointer';

                                        make_script_history(tbody, el, tab_history, 0)();

                                        div = SOM.createElement(contenant, 'div');
                                        div.style.cssFloat = 'left';
                                        div.style.fontSize = '10px';
                                        div.style.marginTop = '2px';
                                        div.style.marginLeft = '4px';

                                        el = SOM.createElement(div, 'a');
                                        el.target = '_blank';
                                        el.href = SOM.USO_URL + '/scripts/show/' + numero_script;
                                        SOM.createTextNode(el, "Web page");

                                        div = SOM.createElement(contenant, 'div');
                                        div.style.cssFloat = 'right';
                                        div.style.fontSize = '10px';
                                        div.style.marginTop = '2px';
                                        div.style.marginRight = '4px';
                                        SOM.createTextNode(div, "Author: " + script_auteur);

                                        SOM.createElement(contenant, 'br');

                                        div = SOM.createElement(contenant, 'div');
                                        div.style.marginBottom = '-10px';
                                        div.style.textAlign = 'center';
                                        div.style.fontWeight = 'bold';
                                        SOM.createTextNode(div, "Update ?");

                                        showMessage(
                                                /*content*/ contenant,
                                                /*header*/  'Script Updater by [<a href="http://scripts-o-maniacs.leforum.eu" target="_blank">SOM</a>]',
                                                /*width*/   500,
                                                /*height*/  undefined,
                                                /*options*/ [ ['Yes', ouvrir_lien_script], ['No'] ]
                                                );
                                    }
                                }
                            } catch(e) {
                                // Il y a eu une erreur (timeout uso?), essayer dans 2h.
                                prochaine_maj = (new Date().getTime() / 1000) + (2 * 60 * 60);
                            }
                            var cle = 'SOM_' + numero_script + '_MAJ';
                            SOM.setObject(cle, prochaine_maj);
                        };
                    };

                    // Ajout d'un event pour récupérer le contenu de l'iframe.
                    window.addEventListener('message',
                            trait_ret_iframe(version_courante, numero_script),
                            true);
                }
            };

            SOM.Tools.mettre_a_jour(SOM.Tools.VERSION, SOM.Tools.NUMERO_SCRIPT);
        }
    )

} else {
    // Script running in update iframe.
    (
        function(f) {
            var s = document.createElement('script');
            s.type = 'application/javascript';
            s.textContent = '(' + f.toString() + ')()';
            (document.body || document.head || document.documentElement).appendChild(s);
            s.parentNode.removeChild(s);
        }
    )(
        function() {
            var NUMERO_SCRIPT = '120825';

            function envoi_info() {
                var destination = window.parent;
                message = String(escape(document.body.textContent));

                if (destination.postMessage) {
                    destination.postMessage(NUMERO_SCRIPT + message, '*');
                }
            }

            envoi_info();
        }
    )
}

